package com.ilink.groundservice.service.impl.AiX;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.groundservice.entity.PO.AiX.AiXDelete;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneBase;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseBase;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseFinish;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseOpus;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneSubPhase;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneSubPhaseOpus;
import com.ilink.groundservice.entity.VO.AiX.AiXPhaseResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXPhaseUpdateInformationResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXPhaseUpdateWorkResponse;
import com.ilink.groundservice.mapper.AiX.AiXDeleteMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneBaseMapper;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseFinishMapper;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseOpusMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneSubPhaseMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneSubPhaseOpusMapper;
import com.ilink.groundservice.service.AiX.AiXScenePhaseBaseService;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseBaseMapper;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPhaseDTO;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPhaseUpdateInformationRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPhaseUpdateWorkRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author LENOVO
* @description 针对表【ai_x_scene_phase_base】的数据库操作Service实现
* @createDate 2025-01-15 11:24:51
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class AiXScenePhaseBaseServiceImpl extends ServiceImpl<AiXScenePhaseBaseMapper, AiXScenePhaseBase>
    implements AiXScenePhaseBaseService{
    private final AiXSceneBaseMapper aiXSceneBaseMapper;
    private final AiXScenePhaseBaseMapper aiXScenePhaseBaseMapper;
    private final AiXSceneSubPhaseMapper aiXSceneSubPhaseMapper;
    private final AiXDeleteMapper aiXDeleteMapper;



    /**
     * @Author ZhangBo
     * @Description 根据场景ID获取所有阶段信息
     * @Date 10:52 2025/1/16
     * @Param
     * @return
     **/
    @Override
    public List<AiXPhaseResponse> getPhaseList(Long sceneId) {
        try {
            // 查询场景的所有阶段信息
            List<AiXScenePhaseBase> phaseBaseList = aiXScenePhaseBaseMapper.selectList(
                new LambdaQueryWrapper<AiXScenePhaseBase>().eq(AiXScenePhaseBase::getSceneId, sceneId)
            );

            // 将查询结果转换为响应对象
            List<AiXPhaseResponse> responseList = phaseBaseList.stream().map(phase -> {
                AiXPhaseResponse response = new AiXPhaseResponse();
                response.setPhaseId(phase.getPhaseId());
                response.setPhaseTitle(phase.getPhaseTitle());
                response.setSortOrder(phase.getSortOrder());
                return response;
            }).collect(Collectors.toList());

            // 根据sortOrder字段进行升序排序
            responseList.sort(Comparator.comparingInt(AiXPhaseResponse::getSortOrder));

            return responseList;
        } catch (Exception e) {
            log.error("查询阶段信息失败，sceneId: " + sceneId, e);
            return new ArrayList<>(); // 如果出错返回空列表
        }
    }

    /**
     * @Author ZhangBo
     * @Description 更新阶段列表
     * @Date 11:09 2025/1/16
     * @Param [phaseRequestList]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    @Transactional
    public R updatePhaseList(Long sceneId, List<AiXPhaseDTO> phaseDTO) {
        try {
            // 遍历接收到的每个阶段请求
            for (AiXPhaseDTO phaseRequest : phaseDTO) {
                log.info(String.valueOf(phaseRequest.getPhaseId()));
                if (phaseRequest.getIsNew() != null && phaseRequest.getIsNew()) {
                    log.info("新增阶段，phaseId: {}", phaseRequest.getPhaseId());
                    // 如果是新增阶段，创建新阶段并插入
                    AiXScenePhaseBase newPhase = new AiXScenePhaseBase();
                    SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
                    Long phaseId =idGenerator.nextId();
                    newPhase.setPhaseId(phaseId);
                    newPhase.setPhaseTitle(phaseRequest.getPhaseTitle());
                    newPhase.setSortOrder(phaseRequest.getSortOrder());
                    newPhase.setIntroduction("您可以在此处简要介绍本阶段的技术手段、关键任务及核心内容，字数不超过200字。"); // 默认阶段简介
                    newPhase.setPhaseTarget("您可以在此处详细介绍本阶段目标，包括主要任务、关键技术和预期成果等，字数不超过200字。"); // 默认阶段目标
                    newPhase.setPhaseScore(0); // 默认阶段分数
                    newPhase.setWorkRequirement("您可以在此处输入本阶段作品要求，包括任务目标、数据也可以不要求提交作品。\n"
                        + "格式及具体内容等，可以分条阐述，字数不超过200字。");
                    newPhase.setWorkScore(0);
                    newPhase.setSceneId(sceneId);
                    aiXScenePhaseBaseMapper.insert(newPhase); // 新增阶段

                    // 新建默认子阶段
                    AiXSceneSubPhase subPhase = new AiXSceneSubPhase();
                    subPhase.setSubPhaseId(idGenerator.nextId());
                    subPhase.setSubPhaseTitle("您可以在此处输入任务的名称");
                    subPhase.setIntroduction("您可以在此处输入任务介绍，包括关键技术、实施方法及预期成果等，字数不超过150字。");
                    subPhase.setSubPhaseTarget("您可以在此处输入任务目标，包括输入输出内容、使用的技术和预期结果等，字数不超过150字。");
                    subPhase.setWorkRequirement("您可以在此处输入作品要求，包括任务步骤、数据格式和数量要求等，可以分条阐述，字数不超过150字。当然，本任务您也可以不要求提交作品。");
                    subPhase.setWorkScore(0);
                    subPhase.setSortOrder(1);
                    subPhase.setPhaseId(phaseId);
                    subPhase.setWorkExist(true);
                    aiXSceneSubPhaseMapper.insert(subPhase);
                }

                if (phaseRequest.getIsOff() != null && phaseRequest.getIsOff()) {
                    log.info("删除阶段，phaseId: {}", phaseRequest.getPhaseId());
                    // 在AiXDelete表中插入删除记录
                    AiXDelete deleteRecord = new AiXDelete();
                    deleteRecord.setDeleteId(new SnowflakeIdGenerator(1, 1).nextId());
                    
                    // 查询phase获取sceneId
                    AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(phaseRequest.getPhaseId());
                    // 查询scene获取areaId 
                    AiXSceneBase scene = aiXSceneBaseMapper.selectById(phase.getSceneId());
                    
                    deleteRecord.setDeletePath(String.format("area/%d/scene/%d/phase/%d", 
                        scene.getAreaId(), phase.getSceneId(), phase.getPhaseId()));
                    deleteRecord.setForeignId(phase.getPhaseId());
                    deleteRecord.setForeignName("ai_x_scene_phase");
                    aiXDeleteMapper.insert(deleteRecord);
                    // 如果是删除阶段，级联删除该阶段
                    aiXScenePhaseBaseMapper.deleteById(phaseRequest.getPhaseId()); // 删除阶段
                }

                if ((phaseRequest.getIsNew() == null || !phaseRequest.getIsNew()) 
                    && (phaseRequest.getIsOff() == null || !phaseRequest.getIsOff())) {
                    log.info("修改阶段，phaseId: {}", phaseRequest.getPhaseId());
                    // 如果是修改阶段，更新该阶段的信息
                    AiXScenePhaseBase existingPhase = aiXScenePhaseBaseMapper.selectById(phaseRequest.getPhaseId());
                    if (existingPhase != null) {
                        existingPhase.setPhaseTitle(phaseRequest.getPhaseTitle());
                        existingPhase.setSortOrder(phaseRequest.getSortOrder());
                        aiXScenePhaseBaseMapper.updateById(existingPhase); // 更新阶段
                    }
                }
            }
            return R.ok("阶段更新成功");
        } catch (Exception e) {
            log.error("更新阶段信息失败: " + e.getMessage(), e);
            return R.error("更新阶段信息失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据阶段ID获取该阶段所有信息
     * @Date 16:02 2025/1/16
     * @Param [phaseId]
     * @return com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseBase
     **/
    @Override
    public AiXScenePhaseBase getPhaseById(Long phaseId) {
        try {
            // 根据 phaseId 查询该阶段的所有信息
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(phaseId);

            if (phase == null) {
                log.error("未找到该阶段信息，phaseId: " + phaseId);
                return null;  // 如果没有找到数据，返回 null 或者自定义错误信息
            }

            return phase;  // 返回查询到的阶段信息
        } catch (Exception e) {
            log.error("获取阶段信息失败，phaseId: " + phaseId, e);
            return null;  // 如果发生异常，返回 null 或者自定义错误信息
        }
    }

    /**
     * @Author ZhangBo
     * @Description 更新阶段基本信息
     * @Date 16:09 2025/1/16
     * @Param [request]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    @Transactional
    public R updatePhaseInstructionById(AiXPhaseUpdateInformationRequest request) {
        try {
            // 查询阶段数据
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(request.getPhaseId());
            if (phase == null) {
                return R.error("未找到该阶段信息，id: " + request.getPhaseId());
            }

            phase.setIntroduction(request.getInformation());

            // 执行更新操作
            aiXScenePhaseBaseMapper.updateById(phase);

            return R.ok("阶段介绍更新成功", request.getInformation());
        } catch (Exception e) {
            log.error("更新阶段介绍失败，id: " + request.getPhaseId(), e);
            return R.error("更新阶段介绍失败");
        }
    }

    @Override
    @Transactional
    public R updatePhaseTargetById(AiXPhaseUpdateInformationRequest request) {
        try {
            // 查询阶段数据
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(request.getPhaseId());
            if (phase == null) {
                return R.error("未找到该阶段信息，id: " + request.getPhaseId());
            }

            phase.setPhaseTarget(request.getInformation());

            // 执行更新操作
            aiXScenePhaseBaseMapper.updateById(phase);

            return R.ok("阶段目标更新成功", request.getInformation());
        } catch (Exception e) {
            log.error("更新阶段目标失败，id: " + request.getPhaseId(), e);
            return R.error("更新阶段目标失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 修改作业要求和作业分数
     * @Date 16:32 2025/1/16
     * @Param [request]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    @Transactional
    public R updateWorkById(AiXPhaseUpdateWorkRequest request) {
        try {
            // 1. 查询该 sceneId 下的所有阶段
            List<AiXScenePhaseBase> phaseList = aiXScenePhaseBaseMapper.selectList(
                new LambdaQueryWrapper<AiXScenePhaseBase>().eq(AiXScenePhaseBase::getSceneId, request.getSceneId())
            );

            // 2. 计算其他阶段的分数总和
            int totalOtherPhaseScore = phaseList.stream()
                .filter(phase -> !phase.getPhaseId().equals(request.getPhaseId())) // 排除当前阶段
                .mapToInt(AiXScenePhaseBase::getPhaseScore)
                .sum();
            
            // 3. 计算当前阶段所有子阶段分数总和
            int totalCurrentPhaseSubPhaseScore = aiXSceneSubPhaseMapper.selectList(
                new LambdaQueryWrapper<AiXSceneSubPhase>()
                    .eq(AiXSceneSubPhase::getPhaseId, request.getPhaseId())
                    .eq(AiXSceneSubPhase::getWorkExist, true)
            ).stream().mapToInt(AiXSceneSubPhase::getWorkScore).sum();


            // 4. 检查当前阶段作业分数是否符合条件
            int totalScore = 100 - totalOtherPhaseScore - totalCurrentPhaseSubPhaseScore;
            if (request.getScore() > totalScore) {
                return R.error("作业分数超限","作业分数不能大于" + totalScore);
            }

            log.info("totalOtherPhaseScore: " + totalOtherPhaseScore);
            log.info("totalCurrentPhaseSubPhaseScore: " + totalCurrentPhaseSubPhaseScore);

            // 5. 根据 phaseId 查询该阶段
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(request.getPhaseId());
            if (phase == null) {
                return R.error("未找到该阶段信息，phaseId: " + request.getPhaseId());
            }

            // 6. 记录作业分数变更的差值，更新作业要求和作业分数。根据差值更新阶段总分数
            Integer scoreMinus = request.getScore() - phase.getWorkScore();
            phase.setWorkRequirement(request.getInformation()); // 更新作业要求
            phase.setWorkScore(request.getScore());            // 更新作业分数
            Integer phaseScore = phase.getPhaseScore() + scoreMinus;
            phase.setPhaseScore(phaseScore);

            // 7. 执行更新
            aiXScenePhaseBaseMapper.updateById(phase);

            AiXPhaseUpdateWorkResponse response = new AiXPhaseUpdateWorkResponse();
            response.setInformation(request.getInformation());
            response.setScore(request.getScore());

            return R.ok("作业信息更新成功",response);
        } catch (Exception e) {
            log.error("更新作业信息失败，phaseId: " + request.getPhaseId(), e);
            return R.error("更新作业信息失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据 phaseId 新增和删除作业，只需要修改 workExist 字段
     * @Date 16:33 2025/1/16
     * @Param [phaseId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    @Transactional
    public R deleteWorkByPhaseId(Long phaseId) {
        try {
            // 根据 phaseId 查询阶段
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(phaseId);
            if (phase == null) {
                return R.error("未找到该阶段信息，phaseId: " + phaseId);
            }

            // 更新 workExist 字段为 false（删除作业）
            phase.setWorkExist(false);  // 将作业标记为不存在
            Integer scoreMinus = -phase.getWorkScore();
            Integer phaseScore = phase.getPhaseScore() + scoreMinus;
            phase.setPhaseScore(phaseScore);
            phase.setWorkScore(0);

            // 执行更新操作
            aiXScenePhaseBaseMapper.updateById(phase);

            return R.ok("作业已删除");
        } catch (Exception e) {
            log.error("删除作业失败，phaseId: " + phaseId, e);
            return R.error("删除作业失败");
        }
    }

    @Override
    @Transactional
    public R insertWorkByPhaseId(Long phaseId) {
        try {
            // 根据 phaseId 查询阶段
            AiXScenePhaseBase phase = aiXScenePhaseBaseMapper.selectById(phaseId);
            if (phase == null) {
                return R.error("未找到该阶段信息，phaseId: " + phaseId);
            }

            // 更新 workExist 字段为 false（删除作业）
            phase.setWorkExist(true);  // 将作业标记为不存在

            // 执行更新操作
            aiXScenePhaseBaseMapper.updateById(phase);

            AiXPhaseUpdateWorkResponse response = new AiXPhaseUpdateWorkResponse();
            response.setInformation(phase.getWorkRequirement());
            response.setScore(phase.getWorkScore());

            return R.ok("作业已新增",response);
        } catch (Exception e) {
            log.error("新增作业失败，phaseId: " + phaseId, e);
            return R.error("新增作业失败");
        }
    }


}




